package com.bw.user.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bw.user.entity.OrderInfoEntity;
import com.bw.user.service.OrderInfoService;
import com.bw.common.utils.IdWorker;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * @ClassName SeckillCousumer
 * @Author Hao_YunKai
 * @Date 2022/3/2 9:39
 */
@Component
public class SeckillConsumer {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = "OrderAddQueue")
    public void orderAddServer(String order, Channel channel, Message message) throws IOException {
        System.out.println("MQ: " + order);
        OrderInfoEntity orderInfoEntity = JSON.parseObject(order, new TypeReference<OrderInfoEntity>() {});
        orderInfoEntity.setId(new IdWorker().nextId());
        orderInfoEntity.setCreateDate(new Date());
        orderInfoService.save(orderInfoEntity);
        // 有库存 添加订单
        redisTemplate.opsForHash().put("goodsSeckillOrder",orderInfoEntity.getUserId().toString() + orderInfoEntity.getGoodsId(), JSON.toJSONString(orderInfoEntity));
        // ack模式 消息手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
